package servlet;

import DBTool.DB;
import bean.Student;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;

@WebServlet("/add")
public class Add extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
            String sql="select * from student";
        ResultSet rs = DB.query(sql);
        ArrayList<Student> list = new ArrayList<>();
        try {
            while (rs.next()){
                int sid = rs.getInt(1);
                String sname = rs.getString(2);
                Student student = new Student(sid, sname);
                list.add(student);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        request.setAttribute("list",list);
        request.getRequestDispatcher("/WEB-INF/add.jsp").forward(request,response);

    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        String sname = request.getParameter("sname");
        String time = request.getParameter("time");
        String type = request.getParameter("type");
        String sql="insert into attence values(?,?,?,?)";
        int i = DB.update(sql, null, time, type, sname);
        if (i >0) {
            response.sendRedirect("/stu");
        }
    }
}
